// datatype:   player      用户 {'datatype':'player', 'name':nickname, 'comm':'reg'}
//                             {'datatype':'player', 'comm':'list', 'player_list':players}
//             msg         消息 { 'datatype':'msg', 'name': nickname, 'content': text.value}
//             room        房间
//全局
let ws
let ws_url = 'ws://localhost:8000/'
let ws_data
let nickname 
let disName
// 载入
onload = function () {
    nickname = localStorage.getItem('nickname')
    if (!nickname) {
        console.log('[LOG] nickname 不存在')
        location = '/chat'
    }
    else {
        document.getElementById('header').innerHTML += nickname;
    }
    ws = new WebSocket(ws_url)
    ws.onopen = function (e) {
        console.log('[LOG] websocket 建立连接:', e.target['url'])
        reg_player()
    }
    ws.onmessage = function (e) {  
        ws_data = JSON.parse(e.data)
        console.log('[LOG] websocket 收到消息:', ws_data)
        refresh(ws_data)
    }
    ws.onclose = function (e) {

        console.log('[LOG] websocket 断开连接.')
        
    }
    ws.onerror = function (e) {
        console.log('[LOG] websocket 连接错误:', e)
    }
    disName = nickname
}

// 登出
function logout() {
    let removeme = {'datatype':'player',  'comm':'remove', 'name':nickname,}
    if (ws) {
        if (ws.readyState == ws.OPEN) {
            send(removeme)
            ws.close()
        }
    }
    localStorage.removeItem('nickname')
    location = '/chat'
}

// 刷新页面内容
function refresh(data) {
    
    let datatype = data['datatype']
    
    // 刷新玩家列表
    if (datatype == 'player') {
        
        let player_list_box = document.getElementById('player-list')
        player_list = data['player_list']
        console.log('[LOG] 收到',datatype,player_list)
        player_list_box.innerHTML = ''
        for(i = 0; i < player_list.length; i++) {
            player_list_box.innerHTML += ('<li id="player">' + player_list[i] + '</li>')
        }         
    }

    // 加载消息
    if (datatype == 'msg') {
        let msgbox = document.getElementById('chat-msg')
        let srcName = data['srcName']
        let content = data['content']
        console.log('[LOG] 收到',datatype,content )
        msgbox.innerHTML += (
            '<div > <div>'
            + srcName +
            '</div> <div><li>'
            + content +
            '</li></div></div>'
        )
    }
}
// 发送消息
function send_msg() {
    let text = document.getElementById('inputbox')
    if (text.value) {
        let data = { 'datatype':'msg', 'srcName': nickname, 'disName':disName, 'content': text.value}
        // 数据-->字符串
        send(data)
        text.value = ''
    }
    else {
        return false
    }
}

function reg_player(){
    let data = {'datatype':'player',  'comm':'reg', 'name':nickname,}
    send(data)
}

// 发送数据
function send(data) {
    let datastr = JSON.stringify(data)
    console.log('[LOG] 数据发送成功:', datastr)
    ws.send(datastr)
}

//发送消息 Ctrl+Enter 快捷键
onkeydown = function (e) {
    if (e['key'] == 'Enter' & e['ctrlKey']) {
        send_msg()
    }
}

onclick = function (e) {
    if(e.target.id == 'player'){
        disName = e.target.innerHTML
    }   
}